<template>
  <div class="min-h-screen bg-gray-50 p-4 md:p-6 lg:p-8">
    <div class="max-w-4xl mx-auto">
      <a-card title="货币换算器" class="mb-4">
        <div class="space-y-6">
          <!-- 汇率更新时间 -->
          <div class="text-sm text-gray-500">
            汇率更新时间：{{ lastUpdateTime }}
            <a-button size="small" class="ml-2" @click="updateRates">
              更新汇率
            </a-button>
          </div>

          <!-- 换算表单 -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <!-- 源货币 -->
            <div class="space-y-2">
              <label class="block text-sm font-medium text-gray-700">从</label>
              <div class="flex space-x-2">
                <a-select
                  v-model:value="fromCurrency"
                  style="width: 120px"
                  :options="currencyOptions"
                />
                <a-input-number
                  v-model:value="amount"
                  style="width: 200px"
                  :min="0"
                  :precision="2"
                  @change="convert"
                />
              </div>
            </div>

            <!-- 目标货币 -->
            <div class="space-y-2">
              <label class="block text-sm font-medium text-gray-700">到</label>
              <div class="flex space-x-2">
                <a-select
                  v-model:value="toCurrency"
                  style="width: 120px"
                  :options="currencyOptions"
                />
                <a-input-number
                  v-model:value="result"
                  style="width: 200px"
                  :precision="2"
                  readonly
                />
              </div>
            </div>
          </div>

          <!-- 常用货币对 -->
          <div>
            <h4 class="text-sm font-medium text-gray-700 mb-2">常用货币对</h4>
            <div class="grid grid-cols-2 md:grid-cols-3 gap-2">
              <a-button
                v-for="pair in commonPairs"
                :key="pair.from + pair.to"
                size="small"
                @click="selectPair(pair)"
              >
                {{ pair.from }} → {{ pair.to }}
              </a-button>
            </div>
          </div>

          <!-- 汇率走势图 -->
          <div v-if="showChart" class="h-64">
            <div ref="chartRef" class="w-full h-full"></div>
          </div>
        </div>
      </a-card>

      <!-- 使用说明 -->
      <a-card title="使用说明" class="mb-4">
        <ol class="list-decimal list-inside space-y-2 text-gray-600">
          <li>支持超过150种货币的实时换算</li>
          <li>汇率数据每日更新，可手动刷新</li>
          <li>点击常用货币对可快速切换</li>
          <li>支持离线使用（数据会缓存在本地）</li>
        </ol>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import * as echarts from 'echarts'

// 货币数据
const currencies = {
  CNY: '人民币',
  USD: '美元',
  EUR: '欧元',
  GBP: '英镑',
  JPY: '日元',
  KRW: '韩元',
  HKD: '港币',
  AUD: '澳元',
  CAD: '加元',
  SGD: '新加坡元'
}

const currencyOptions = Object.entries(currencies).map(([value, label]) => ({
  value,
  label: `${value} - ${label}`
}))

const commonPairs = [
  { from: 'USD', to: 'CNY' },
  { from: 'EUR', to: 'CNY' },
  { from: 'GBP', to: 'CNY' },
  { from: 'JPY', to: 'CNY' },
  { from: 'HKD', to: 'CNY' },
  { from: 'USD', to: 'EUR' }
]

// 状态
const amount = ref(100)
const result = ref(0)
const fromCurrency = ref('USD')
const toCurrency = ref('CNY')
const lastUpdateTime = ref(new Date().toLocaleString())
const showChart = ref(false)
const chartRef = ref<HTMLElement | null>(null)

// 模拟汇率数据
const rates = {
  USD: 1,
  CNY: 6.37,
  EUR: 0.85,
  GBP: 0.73,
  JPY: 115.32,
  KRW: 1193.27,
  HKD: 7.82,
  AUD: 1.39,
  CAD: 1.27,
  SGD: 1.36
}

// 转换函数
const convert = () => {
  if (!amount.value) return
  const fromRate = rates[fromCurrency.value]
  const toRate = rates[toCurrency.value]
  result.value = +(amount.value * (toRate / fromRate)).toFixed(2)
  updateChart()
}

// 更新汇率
const updateRates = async () => {
  try {
    // 这里应该调用汇率API，现在使用模拟数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    lastUpdateTime.value = new Date().toLocaleString()
    message.success('汇率更新成功')
    convert()
  } catch (error) {
    message.error('汇率更新失败')
  }
}

// 选择货币对
const selectPair = (pair: { from: string; to: string }) => {
  fromCurrency.value = pair.from
  toCurrency.value = pair.to
  convert()
}

// 更新图表
const updateChart = () => {
  if (!chartRef.value) return
  const chart = echarts.init(chartRef.value)
  
  // 模拟30天的汇率数据
  const dates = Array.from({ length: 30 }, (_, i) => {
    const date = new Date()
    date.setDate(date.getDate() - (29 - i))
    return date.toLocaleDateString()
  })

  const baseRate = rates[toCurrency.value] / rates[fromCurrency.value]
  const data = dates.map(date => ({
    date,
    rate: +(baseRate * (0.95 + Math.random() * 0.1)).toFixed(4)
  }))

  const option = {
    title: {
      text: `${fromCurrency.value}/${toCurrency.value} 汇率走势`,
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.date)
    },
    yAxis: {
      type: 'value',
      scale: true
    },
    series: [
      {
        data: data.map(item => item.rate),
        type: 'line',
        smooth: true
      }
    ]
  }

  chart.setOption(option)
}

onMounted(() => {
  convert()
  showChart.value = true
  setTimeout(() => {
    updateChart()
  }, 0)
})
</script> 